package com.zxy.lagouzuoye;

import org.omg.Messaging.SYNC_WITH_TRANSPORT;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2020/10/24
 */
public class ApplicationContext {
    //存放bean的容器
    Map<String,Object> containner = new HashMap<String, Object>();
    public ApplicationContext(){
        //ApplicationContext启动时会扫描自己所在包下所有的类
        String name = ApplicationContext.class.getPackage().getName();
        List<Class<?>> classes = ClassUtil.getClasses(name);
        for(Class clazz:classes)
        {   //选取被Service注解修饰过的类
            if(clazz.isAnnotationPresent(Service.class))
            {
                Service annotation =(Service) clazz.getAnnotation(Service.class);
                String id = annotation.id();
                try {//将类实例化放入容器
                    Object o = clazz.newInstance();
                    this.containner.put(id,o);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        for(Map.Entry<String,Object> entry:this.containner.entrySet())
        {   //扫描容器中已有的bean，遍历他们的字段
            Object aClass = entry.getValue();
            Field[] fields = aClass.getClass().getFields();
            for(Field field:fields)
            {   //选取被autowird注解修饰过的类
                if(field.isAnnotationPresent(Autowired.class))
                {   //从容器中选出bean将其注入字段
                    Autowired autowired=field.getAnnotation(Autowired.class);
                    Object o = this.containner.get(autowired.id());
                    System.out.println("----------------"+o);
                    field.setAccessible(true);
                    try {
                        field.set(aClass,o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        for(Map.Entry<String,Object> entry:this.containner.entrySet())
        {   //选取Transaction修饰过的方法
            Object value = entry.getValue();
            Method[] methods = value.getClass().getMethods();
            for(Method method: methods)
            {   //生成代理对象，放入容器
                if(method.isAnnotationPresent(Transaction.class))
                {
                    Object cglibProxy = ProxyFactory.getCglibProxy(value);
                    containner.put(entry.getKey(),cglibProxy);
                }
            }
        }
    }


    public Object getBeanById(String id)
    {
        return this.containner.get(id);
    }


}
